// MGC
//
// MGImagePickerTool.m
// MGWallet
//
// Created by MGC on 2017/11/16.
// Copyright © 2017年 HFW. All rights reserved.
//
// @ description <#描述#> 

#import "MGImagePickerTool.h"

#import <TZImagePickerController/TZImagePickerController.h>
#import <TZImagePickerController/TZGifPhotoPreviewController.h>
#import <TZImagePickerController/TZVideoPlayerController.h>

#import <TZImagePickerController/TZImageManager.h>
#import <TZImagePickerController/TZLocationManager.h>

#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>

@interface MGImagePickerTool ()<TZImagePickerControllerDelegate, UIActionSheetDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate>
{
    NSMutableArray *_selectedPhotos;
    NSMutableArray *_selectedAssets;
    BOOL _isSelectOriginalPhoto;
}

/** 当前控制器 */
@property (nonatomic, strong) UIViewController *currentVC;

@property (strong, nonatomic) CLLocation *location;
@property (nonatomic, strong) UIImagePickerController *imagePickerVc;
@end

@implementation MGImagePickerTool

#pragma mark - TZImagePickerController
/**
 *  弹出图片选择控制器
 */
- (void)pushTZImagePickerController {
    if (self.maxCount <= 0) {
        return;
    }
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:self.maxCount columnNumber:self.columnNumber delegate:self pushPhotoPickerVc:YES];
    
#pragma mark - 四类个性化设置，这些参数都可以不传，此时会走默认设置
    imagePickerVc.isSelectOriginalPhoto = _isSelectOriginalPhoto;
    
    if (self.maxCount > 1) {
        imagePickerVc.selectedAssets = _selectedAssets; // 目前已经选中的图片数组
    }
    imagePickerVc.allowTakePicture = self.isShowTakePhotoBtn; // 在内部显示拍照按钮
    
    // 2. Set the appearance
    // 2. 在这里设置imagePickerVc的外观
    imagePickerVc.naviBgColor = self.navBgColor;
    imagePickerVc.naviTitleFont = self.navTitleFont;
    imagePickerVc.naviTitleColor = self.navTitleColor;
    imagePickerVc.barItemTextFont = self.navItemTextFont;
    imagePickerVc.barItemTextColor = self.navItemTextColor;
    imagePickerVc.oKButtonTitleColorDisabled = self.oKButtonTitleColorDisabled;
    imagePickerVc.oKButtonTitleColorNormal = self.oKButtonTitleColorNormal;
    imagePickerVc.navigationBar.translucent = NO;
    
    // 3. Set allow picking video & photo & originalPhoto or not
    // 3. 设置是否可以选择视频/图片/原图
    imagePickerVc.allowPickingVideo = self.isAllowPickingVideo;
    imagePickerVc.allowPickingImage = self.isAllowPickingImage;
    imagePickerVc.allowPickingOriginalPhoto = self.isAllowPickingOriginalPhoto;
    imagePickerVc.allowPickingGif = self.isAllowPickingGif;
    
    // 4. 照片排列按修改时间升序
    imagePickerVc.sortAscendingByModificationDate = self.isSortAscending;
    
    imagePickerVc.showSelectBtn = NO;
    imagePickerVc.needCircleCrop = self.isNeedCircleCrop;
    if (self.isNeedCircleCrop) {
        imagePickerVc.circleCropRadius = self.circleCropRadius;
    }
    imagePickerVc.allowCrop = self.isAllowCrop;
    imagePickerVc.cropRect = self.cropRect;
    imagePickerVc.isStatusBarDefault = NO;
#pragma mark - 到这里为止
    
    [self.currentVC presentViewController:imagePickerVc animated:YES completion:nil];
}

#pragma mark - UIImagePickerController
- (void)takePhoto {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if ((authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) && iOS7Later) {
        // 无相机权限 做一个友好的提示
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
        [alert show];
        
        
    } else if (authStatus == AVAuthorizationStatusNotDetermined) {
        // fix issue 466, 防止用户首次拍照拒绝授权时相机页黑屏
        if (iOS7Later) {
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if (granted) {
                    dispatch_sync(dispatch_get_main_queue(), ^{
                        [self takePhoto];
                    });
                }
            }];
        } else {
            [self takePhoto];
        }
        // 拍照之前还需要检查相册权限
    } else if ([TZImageManager authorizationStatus] == 2) { // 已被拒绝，没有相册权限，将无法保存拍的照片
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法访问相册" message:@"请在iPhone的""设置-隐私-相册""中允许访问相册" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
        alert.tag = 1;
        [alert show];
    } else if ([TZImageManager authorizationStatus] == 0) { // 未请求过相册权限
        [[TZImageManager manager] requestAuthorizationWithCompletion:^{
            [self takePhoto];
        }];
    } else {
        [self pushImagePickerController];
    }
}

// 调用相机
- (void)pushImagePickerController {
    // 提前定位
    __weak typeof(self) weakSelf = self;
    [[TZLocationManager manager] startLocationWithSuccessBlock:^(CLLocation *location, CLLocation *oldLocation) {
        weakSelf.location = location;
    } failureBlock:^(NSError *error) {
        weakSelf.location = nil;
    }];
    
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        self.imagePickerVc.sourceType = sourceType;
        if(iOS8Later) {
            _imagePickerVc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        }
        [self.currentVC presentViewController:_imagePickerVc animated:YES completion:nil];
    } else {
        DLog(@"模拟器中无法打开照相机,请在真机中使用");
    }
}

- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        TZImagePickerController *tzImagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
        tzImagePickerVc.sortAscendingByModificationDate = self.isSortAscending;
        [tzImagePickerVc showProgressHUD];
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        
        // save photo and get asset / 保存图片，获取到asset
        [[TZImageManager manager] savePhotoWithImage:image location:self.location completion:^(NSError *error){
            if (error) {
                [tzImagePickerVc hideProgressHUD];
                DLog(@"图片保存失败 %@",error);
            } else {
                [[TZImageManager manager] getCameraRollAlbum:NO allowPickingImage:YES completion:^(TZAlbumModel *model) {
                    [[TZImageManager manager] getAssetsFromFetchResult:model.result allowPickingVideo:NO allowPickingImage:YES completion:^(NSArray<TZAssetModel *> *models) {
                        [tzImagePickerVc hideProgressHUD];
                        TZAssetModel *assetModel = [models firstObject];
                        if (tzImagePickerVc.sortAscendingByModificationDate) {
                            assetModel = [models lastObject];
                        }
                        if (self.isAllowCrop) { // 允许裁剪,去裁剪
                            TZImagePickerController *imagePicker = [[TZImagePickerController alloc] initCropTypeWithAsset:assetModel.asset photo:image completion:^(UIImage *cropImage, id asset) {
                                [self refreshCollectionViewWithAddedAsset:asset image:cropImage];
                            }];
                            imagePicker.needCircleCrop = self.isNeedCircleCrop;
                            imagePicker.circleCropRadius = self.circleCropRadius;
                            imagePicker.cropRect = self.cropRect;
                            [self.currentVC presentViewController:imagePicker animated:YES completion:nil];
                        } else {
                            [self refreshCollectionViewWithAddedAsset:assetModel.asset image:image];
                        }
                    }];
                }];
            }
        }];
    }
}

- (void)refreshCollectionViewWithAddedAsset:(id)asset image:(UIImage *)image {
    if (!_selectedAssets) {
        _selectedAssets = [NSMutableArray array];
    }
    
    if (!_selectedPhotos) {
        _selectedPhotos = [NSMutableArray array];
    }
    
    [_selectedAssets addObject:asset];
    [_selectedPhotos addObject:image];
    
    if (self.refreshSelectedImagesBlock) {
        self.refreshSelectedImagesBlock(_selectedAssets, _selectedPhotos);
    }
    
    if ([asset isKindOfClass:[PHAsset class]]) {
        PHAsset *phAsset = asset;
        DLog(@"location:%@",phAsset.location);
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    if ([picker isKindOfClass:[UIImagePickerController class]]) {
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) { // take photo / 去拍照
        [self takePhoto];
    } else if (buttonIndex == 1) {
        [self pushTZImagePickerController];
    }
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) { // 去设置界面，开启相机访问权限
        if (iOS8Later) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        } else {
            NSURL *privacyUrl;
            if (alertView.tag == 1) {
                privacyUrl = [NSURL URLWithString:@"prefs:root=Privacy&path=PHOTOS"];
            } else {
                privacyUrl = [NSURL URLWithString:@"prefs:root=Privacy&path=CAMERA"];
            }
            if ([[UIApplication sharedApplication] canOpenURL:privacyUrl]) {
                [[UIApplication sharedApplication] openURL:privacyUrl];
            } else {
                UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"抱歉" message:@"无法跳转到隐私设置页面，请手动前往设置页面，谢谢" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
                [alert show];
            }
        }
    }
}

#pragma mark - TZImagePickerControllerDelegate
/// 用户点击了取消
- (void)tz_imagePickerControllerDidCancel:(TZImagePickerController *)picker {
    // DLog(@"cancel");
}

// 这个照片选择器会自己dismiss，当选择器dismiss的时候，会执行下面的代理方法
// 如果isSelectOriginalPhoto为YES，表明用户选择了原图
// 你可以通过一个asset获得原图，通过这个方法：[[TZImageManager manager] getOriginalPhotoWithAsset:completion:]
// photos数组里的UIImage对象，默认是828像素宽，你可以通过设置photoWidth属性的值来改变它
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    
    _selectedPhotos = [NSMutableArray arrayWithArray:photos];
    _selectedAssets = [NSMutableArray arrayWithArray:assets];
    _isSelectOriginalPhoto = isSelectOriginalPhoto;
    
    if (self.refreshSelectedImagesBlock) {
        self.refreshSelectedImagesBlock(_selectedAssets, _selectedPhotos);
    }
}

// 如果用户选择了一个gif图片，下面的handle会被执行
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingGifImage:(UIImage *)animatedImage sourceAssets:(id)asset {
    _selectedPhotos = [NSMutableArray arrayWithArray:@[animatedImage]];
    _selectedAssets = [NSMutableArray arrayWithArray:@[asset]];
    
    if (self.refreshSelectedImagesBlock) {
        self.refreshSelectedImagesBlock(_selectedAssets, _selectedPhotos);
    }
}

#pragma mark - Private Methods
/**
 *  删除一张图片
 */
- (void)deleteAImageAtIndex:(NSInteger)index
{
    [_selectedPhotos removeObjectAtIndex:index];
    [_selectedAssets removeObjectAtIndex:index];
    
    if (self.refreshSelectedImagesBlock) {
        self.refreshSelectedImagesBlock(_selectedAssets, _selectedPhotos);
    }
}

/**
 *  选择图片
 */
- (void)goToSelectPhotosAtIndex:(NSInteger)index
{
    if (index == _selectedPhotos.count) {
        BOOL showSheet = self.isShowSheet;
        if (showSheet) {
            UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"去相册选择", nil];
            [sheet showInView:self.currentVC.view];
        } else {
            [self pushTZImagePickerController];
        }
    } else { // preview photos or video / 预览照片或者视频
        id asset = _selectedAssets[index];
        BOOL isVideo = NO;
        if ([asset isKindOfClass:[PHAsset class]]) {
            PHAsset *phAsset = asset;
            isVideo = phAsset.mediaType == PHAssetMediaTypeVideo;
        } else if ([asset isKindOfClass:[ALAsset class]]) {
            ALAsset *alAsset = asset;
            isVideo = [[alAsset valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypeVideo];
        }
        if ([[asset valueForKey:@"filename"] containsString:@"GIF"] && self.isAllowPickingGif) {
            TZGifPhotoPreviewController *vc = [[TZGifPhotoPreviewController alloc] init];
            TZAssetModel *model = [TZAssetModel modelWithAsset:asset type:TZAssetModelMediaTypePhotoGif timeLength:@""];
            vc.model = model;
            [self.currentVC presentViewController:vc animated:YES completion:nil];
        } else if (isVideo) { // perview video / 预览视频
            TZVideoPlayerController *vc = [[TZVideoPlayerController alloc] init];
            TZAssetModel *model = [TZAssetModel modelWithAsset:asset type:TZAssetModelMediaTypeVideo timeLength:@""];
            vc.model = model;
            [self.currentVC presentViewController:vc animated:YES completion:nil];
        } else { // preview photos / 预览照片
            TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithSelectedAssets:_selectedAssets selectedPhotos:_selectedPhotos index:index];
            imagePickerVc.maxImagesCount = self.maxCount;
            imagePickerVc.allowPickingOriginalPhoto = self.isAllowPickingOriginalPhoto;
            imagePickerVc.isSelectOriginalPhoto = _isSelectOriginalPhoto;
            [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
                _selectedPhotos = [NSMutableArray arrayWithArray:photos];
                _selectedAssets = [NSMutableArray arrayWithArray:assets];
                _isSelectOriginalPhoto = isSelectOriginalPhoto;
                
                if (self.refreshSelectedImagesBlock) {
                    self.refreshSelectedImagesBlock(_selectedAssets, _selectedPhotos);
                }
            }];
            [self.currentVC presentViewController:imagePickerVc animated:YES completion:nil];
        }
    }
}

#pragma mark - Setter
- (void)setShowTakePhotoBtn:(BOOL)showTakePhotoBtn
{
    _showTakePhotoBtn = showTakePhotoBtn;
    
    if (showTakePhotoBtn) {
        self.allowPickingImage = showTakePhotoBtn;
    }
}

- (void)setShowSheet:(BOOL)showSheet
{
    _showSheet = showSheet;
    
    if (showSheet) {
        self.allowPickingImage = showSheet;
    }
}

- (void)setAllowPickingOriginalPhoto:(BOOL)allowPickingOriginalPhoto
{
    _allowPickingOriginalPhoto = allowPickingOriginalPhoto;
    
    if (allowPickingOriginalPhoto) {
        self.allowPickingImage = allowPickingOriginalPhoto;
        self.needCircleCrop = !allowPickingOriginalPhoto;
        self.allowCrop = !allowPickingOriginalPhoto;
    }
}

- (void)setAllowPickingImage:(BOOL)allowPickingImage
{
    _allowPickingImage = allowPickingImage;
    
    if (!allowPickingImage) {
        self.allowPickingOriginalPhoto = allowPickingImage;
        self.showTakePhotoBtn = allowPickingImage;
        self.allowPickingVideo = !allowPickingImage;
        self.allowPickingGif = allowPickingImage;
    }
}

- (void)setAllowPickingGif:(BOOL)allowPickingGif
{
    _allowPickingGif = allowPickingGif;
    if (allowPickingGif) {
        self.allowPickingImage = allowPickingGif;
    }
}

- (void)setAllowPickingVideo:(BOOL)allowPickingVideo
{
    _allowPickingVideo = allowPickingVideo;
    if (!allowPickingVideo) {
        self.allowPickingImage = !allowPickingVideo;
    }
}

- (void)setAllowCrop:(BOOL)allowCrop
{
    _allowCrop = allowCrop;
    
    if (allowCrop) {
        self.maxCount = 1;
        self.allowPickingOriginalPhoto = !allowCrop;
    } else {
        self.needCircleCrop = allowCrop;
    }
}

- (void)setNeedCircleCrop:(BOOL)needCircleCrop
{
    _needCircleCrop = needCircleCrop;
    
    if (needCircleCrop) {
        self.maxCount = 1;
        self.allowPickingOriginalPhoto = !needCircleCrop;
        self.allowCrop = needCircleCrop;
    }
}

#pragma mark - LazyLoad
- (UIImagePickerController *)imagePickerVc {
    if (_imagePickerVc == nil) {
        _imagePickerVc = [[UIImagePickerController alloc] init];
        _imagePickerVc.delegate = self;
        // set appearance / 改变相册选择页的导航栏外观
        _imagePickerVc.navigationBar.barTintColor = kMainColor;
        _imagePickerVc.navigationBar.tintColor = white_color;
        UIBarButtonItem *tzBarItem, *BarItem;
        if (iOS9Later) {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
            BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]];
        } else {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedIn:[TZImagePickerController class], nil];
            BarItem = [UIBarButtonItem appearanceWhenContainedIn:[UIImagePickerController class], nil];
        }
        NSDictionary *titleTextAttributes = [tzBarItem titleTextAttributesForState:UIControlStateNormal];
        [BarItem setTitleTextAttributes:titleTextAttributes forState:UIControlStateNormal];
    }
    return _imagePickerVc;
}

- (UIViewController *)currentVC
{
    if (!_currentVC) {
        _currentVC = [QSAppTool currentViewController];
    }
    
    return _currentVC;
}
@end
